import $storage from '@/core/storage'

function time() {
    return parseInt(Math.round(new Date() / 1000));
};

function datetime(format, timestamp) {
    if (typeof format === 'undefined' || format === null) {
        format = 'Y-m-d h:i:s';
    }
    if (typeof timestamp === 'undefined' || timestamp === null) {
        timestamp = this.time();
    }
    const d = new Date();
    d.setTime(timestamp * 1000);
    const date = {
        "Y": d.getFullYear(),
        "m+": (d.getMonth() + 1) < 10 ? `0${d.getMonth() + 1}` : (d.getMonth() + 1),
        "d+": d.getDate() < 10 ? `0${d.getDate()}` : d.getDate(),
        "h+": d.getHours() < 10 ? `0${d.getHours()}` : d.getHours(),
        "i+": d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes(),
        "s+": d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds(),
        "q+": Math.floor((d.getMonth() + 3) / 3),
        "S+": d.getMilliseconds(),
    };
    for (let k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ?
                date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
};

function timeDifference(start_at, end_at) {
    let times = parseInt((end_at - start_at) / 1000);
    let day = 0,
        hour = 0,
        minute = 0,
        second = 0;

    if (times > 0) {
        day = Math.floor(times / (60 * 60 * 24));
        hour = Math.floor(times / (60 * 60)) - (day * 24);
        minute = Math.floor(times / 60) - (day * 24 * 60) - (hour * 60);
        second = Math.floor(times) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
    } else {
        return null;
    }

    return {
        d: day,
        h: hour < 10 ? ('0' + hour) : hour,
        m: minute < 10 ? ('0' + minute) : minute,
        s: second < 10 ? ('0' + second) : second,
    };
};

function earthDistance(location1, location2) {
    const lat1 = parseFloat(location1.lat);
    const lng1 = parseFloat(location1.lng);
    const lat2 = parseFloat(location2.lat);
    const lng2 = parseFloat(location2.lng);

    const EARTH_RADIUS = 6378137.0; //单位M
    const PI = Math.PI;

    function getRad(d) {
        return d * PI / 180.0;
    }

    let f = getRad((lat1 + lat2) / 2);
    let g = getRad((lat1 - lat2) / 2);
    let l = getRad((lng1 - lng2) / 2);

    let sg = Math.sin(g);
    let sl = Math.sin(l);
    let sf = Math.sin(f);

    let s, c, w, r, d, h1, h2;
    let a = EARTH_RADIUS;
    let fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
};

function randomString(length) {
    const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
};

let timer, flag;

function throttle(func, wait = 500, immediate = true) {
    if (immediate) {
        if (!flag) {
            flag = true;
            typeof func === 'function' && func();
            timer = setTimeout(() => {
                flag = false;
            }, wait);
        }
    } else {
        if (!flag) {
            flag = true
            timer = setTimeout(() => {
                flag = false
                typeof func === 'function' && func();
            }, wait);
        }

    }
}

let timeout = null;

function debounce(func, wait = 500, immediate = false) {
    if (timeout !== null) clearTimeout(timeout);
    if (immediate) {
        let callNow = !timeout;
        timeout = setTimeout(function () {
            timeout = null;
        }, wait);
        if (callNow) typeof func === 'function' && func();
    } else {
        timeout = setTimeout(function () {
            typeof func === 'function' && func();
        }, wait);
    }
}

function px2rpx(px) {
    let { windowWidth } = $storage.get('system_config');
    windowWidth = (windowWidth > 750) ? 750 : windowWidth;
    return 750 * (px / windowWidth);
}

function rpx2px(rpx) {
    let { windowWidth } = $storage.get('system_config');
    windowWidth = (windowWidth > 750) ? 750 : windowWidth;
    return (rpx / 750) * windowWidth;
}

function toPage(url, options, type) {
    if (typeof type === "undefined") {
        type = "navigate";
    }
    let params = {
        ...{ url: url, },
        ...options
    };
    switch (type) {
        case "reload":
            let pages = getCurrentPages();
            currentPage = pages[pages.length - 1];
            currentPage.onShow(currentPage.options);
            break;
        case "back":
            uni.navigateBack({ ...{ delta: 1 }, ...options });
            break;
        case "relaunch":
            uni.reLaunch(params);
            break;
        case "redirect":
            uni.redirectTo(params);
            break;
        case "switch":
            uni.switchTab(params);
            break;
        case "navigate":
        default:
            uni.navigateTo(params);
            break;
    }
}

let toastTimer;
function toast(title, options) {
    if (typeof options === "undefined") {
        options = {};
    }
    return new Promise((resolve, reject) => {
        if (!options.duration) {
            options.duration = 1500;
        }
        uni.showToast({
            ...{ title: title, icon: "none" },
            ...options
        });
        clearTimeout(toastTimer);
        toastTimer = setTimeout(() => {
            resolve();
        }, options.duration);
    })
}

function formatNumber(num, limit) {
    num = parseFloat(num);
    limit = limit ? limit : 2;
    return num > 0 ? num.toFixed(limit) : 0;
}

function chooseImage(count) {
    return new Promise((resolve, reject) => {
        let tempFiles = [];
        // #ifdef H5
        uni.chooseImage({
            count: count,
            success(r) {
                r.tempFiles.forEach((item, index) => {
                    tempFiles.push({
                        path: r.tempFilePaths[index],
                        size: item.size,
                    });
                });
                resolve(tempFiles);
            },
            fail(e) {
                reject(e);
            }
        });
        // #endif
        // #ifdef MP-WEIXIN
        uni.chooseMedia({
            count: count,
            mediaType: ["image"],
            success(r) {
                r.tempFiles.forEach(item => {
                    tempFiles.push({
                        path: item.tempFilePath,
                        size: item.size,
                    });
                });
                resolve(tempFiles);
            },
            fail(e) {
                reject(e);
            }
        });
        // #endif
    });
}

function callPhone(phoneNumber) {
    uni.makePhoneCall({
        phoneNumber: phoneNumber
    });
}

export default {
    time,
    datetime,
    timeDifference,
    earthDistance,
    randomString,
    throttle,
    debounce,
    px2rpx,
    rpx2px,
    toPage,
    toast,
    formatNumber,
    chooseImage,
    callPhone,
}
